package com.nercel.dsj.gksales.service.impl;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.nercel.dsj.gksales.constant.RedisKeyConstent;
import com.nercel.dsj.gksales.exception.ResponseCode;
import com.nercel.dsj.gksales.exception.RestApiException;
import com.nercel.dsj.gksales.model.dto.CouponParamsDTO;
import com.nercel.dsj.gksales.model.entity.Coupon;
import com.nercel.dsj.gksales.service.CouponService;
import com.nercel.dsj.gksales.service.SmsService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CouponServiceImpl implements CouponService {

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private SmsService smsService;

	@Value("${app.gkServiceApi}")
	private String gkServiceApi;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	private final String couponUrl = "/api/v1/coupons";

	@Override
	public void createActivationCode(CouponParamsDTO paramsDTO) {
		HttpHeaders headers = new HttpHeaders(); // http请求头
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8); // 请求头设置属性
		HttpEntity<CouponParamsDTO> requestEntity = new HttpEntity<>(paramsDTO, headers);
		ResponseEntity<Coupon> responseEntity = restTemplate.postForEntity(gkServiceApi + couponUrl, requestEntity,
				Coupon.class);
		if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
			Coupon coupon = responseEntity.getBody();
			log.info("手机号为：{}的用户，发送激活码：{}成功！", paramsDTO.getPhone(), coupon.getCode());
			// 激活成功则将用户的openId保存到redis,有效时长为48小时
			stringRedisTemplate.opsForValue().set(RedisKeyConstent.OPENID + ":" + paramsDTO.getOpenId(),
					paramsDTO.getPhone(), 48, TimeUnit.HOURS);
			smsService.sendActivationCode(paramsDTO.getPhone(), coupon.getCode());
		} else {
			log.error("向service端发送请求：{}时返回异常，返回码为：{}", (gkServiceApi + couponUrl), responseEntity.getStatusCode());
			throw new RestApiException(ResponseCode.INTERNAL_SERVER_ERROR);
		}
	}

}
